<template>
  <view class="appointment-form">
    <view class="form-section">
      <view class="form-item">
        <text>预约日期</text>
        <picker style="width: 100%; height: 92rpx;" mode="date" :value="formData.visitDate" @change="onDateChange">
          <view class="picker">{{ formData.visitDate || '请选择日期' }}</view>
        </picker>
      </view>
      <view class="form-item">
        <text>预约时间</text>
        <view class="time-grid">
          <view
            v-for="t in times"
            :key="t"
            class="time-chip"
            :class="{ active: formData.visitTime === t }"
            @tap="selectTime(t)"
          >{{ t }}</view>
        </view>
      </view>
      <view class="form-item">
        <text>参观人数</text>
        <picker style="width: 100%; height: 92rpx;" :range="peopleRange" :value="getPeopleIndex()" @change="onPeopleChange">
          <view class="picker">{{ formData.visitorCount }}</view>
        </picker>
      </view>
      <view class="form-item">
        <text>联系人</text>
        <input class="input" v-model="formData.contactName" placeholder="请输入姓名" maxlength="10" />
      </view>
      <view class="form-item">
        <text>联系电话</text>
        <input class="input" v-model="formData.contactPhone" placeholder="请输入手机号" maxlength="11" type="number" />
      </view>
      <view class="form-item">
        <text>电子邮箱</text>
        <input class="input" v-model="formData.email" placeholder="请输入邮箱地址" maxlength="40" />
      </view>
      <view class="form-item">
        <text>公司名称</text>
        <input class="input" v-model="formData.belongCompany" placeholder="请输入公司名称" maxlength="40" />
      </view>
      <view class="form-item">
        <text>备注需求</text>
        <textarea class="remark" v-model="formData.remarks" placeholder="请输入您的特殊需求" maxlength="100" />
      </view>
      <button 
        class="btn-primary" 
        @click="handleSubmit" 
        :disabled="submitting"
      >
        {{ getSubmitButtonText() }}
      </button>
    </view>
  </view>
</template>

<script>
import { validatePhone, validateEmail } from '@/utils/validation.js'
import { API } from '@/utils/api.js'
export default {
  name: 'AppointmentForm',
  props: {
    warehouseId: {
      type: String,
      default: ''
    },

  },
  data() {
    return {
      formData: {
        appointmentId: null, // 预约ID
        warehouseId: '', // 仓库ID
        visitDate: '', // 预约日期 (对应后端的 visitDate)
        visitTime: '', // 预约时间 (对应后端的 visitTime)
        visitorCount: '1人', // 参观人数 (对应后端的 visitorCount)
        contactName: '', // 联系人姓名 (对应后端的 contactName)
        contactPhone: '', // 联系电话 (对应后端的 contactPhone)
        email: '', // 电子邮箱
        remarks: '', // 备注信息 (对应后端的 remarks)
        belongCompany: '', // 所属公司
      },
      warehouseInfo: {},
      times: ['09:00', '10:00', '11:00', '13:00', '14:00', '15:00'],
      peopleRange: ['1人', '2人', '3人', '4人', '5人+'],
      submitting: false,
      submitText: '立即预约'
    }
  },
  watch: {
    warehouseId: {
      immediate: true,
      handler(newVal) {
        if (newVal) this.fetchWarehouseInfo(newVal)
      }
    }
  },
  mounted() {
    // 移除checkToday接口调用
  },
  methods: {

    async fetchWarehouseInfo(warehouseId) {
      try {
        // 设置仓库ID
        this.formData.warehouseId = warehouseId;
        
        // 获取用户信息设置申请人ID
        const userInfo = uni.getStorageSync('userInfo');
        if (userInfo && userInfo.id) {
          this.formData.userId = userInfo.id;
        }
        // 判断token是否存在，如果不存在则直接返回
        const token = uni.getStorageSync('user-token');
        if (!token) {
          return;
        }
        // 获取预约信息（如果存在）
        const res = await API.appointment.getAppointmentByWarehouseId(warehouseId);
        console.log("预约信息--res",res);
        const data = res[0]
        if (data) {
          // 将后端数据映射到前端表单
          this.formData = {
            ...this.formData, // 保留当前数据
            appointmentId: data.appointmentId,
            visitDate: data.visitDate,
            visitTime: data.visitTime,
            visitorCount: data.visitorCount || '1人',
            contactName: data.contactName,
            contactPhone: data.contactPhone,
            email: data.email,
            remarks: data.remarks,
            belongCompany: data.belongCompany,
            status: data.status || 0,
            userId: data.userId
          };
          
          // 如果已有预约，显示取消预约按钮
          if (data.appointmentId) {
              this.$emit('hasAppointment', true);
            // this.$emit('update:submitText', '取消预约');
            this.submitText = '取消预约'
          }
          else {
            this.$emit('hasAppointment', false);
          }
        }
      } catch (error) {
        console.error('获取仓库信息失败:', error);
      }
    },
    onDateChange(e) {
      this.formData.visitDate = e.detail.value
      this.$emit('date-change', e.detail.value)
    },
    onPeopleChange(e) {
      const index = e.detail.value;
      this.formData.visitorCount = this.peopleRange[index];
      this.$emit('people-change', this.peopleRange[index]);
    },
    selectTime(t) {
      this.formData.visitTime = t
      this.$emit('time-change', t)
    },
    validateForm() {
      const errors = []
      
      if (!this.formData.visitDate) {
        errors.push('请选择预约日期')
      }
      if (!this.formData.visitTime) {
        errors.push('请选择预约时间')
      }
      if (!this.formData.contactName.trim()) {
        errors.push('请输入联系人姓名')
      }
      if (!this.formData.contactPhone.trim() || !validatePhone(this.formData.contactPhone)) {
        errors.push('请输入正确的手机号')
      }
      if (this.formData.email && !validateEmail(this.formData.email)) {
        errors.push('请输入正确的邮箱地址')
      }
     // 校验所属公司字段（可选，如果需要必填可取消注释）
      if (!this.formData.belongCompany.trim()) {
        errors.push('请输入所属公司')
      }
      return errors
    },
    async handleSubmit() {
      const errors = this.validateForm()
      if (errors.length > 0) {
        uni.showToast({ 
          title: errors[0], 
          icon: 'none' 
        })
        return
      }
      
      this.submitting = true
      
      try {
        if (this.submitText === '取消预约') {
          // 取消预约
          const res = await API.appointment.cancel(this.formData.appointmentId)
          if (res.code === 200) {
            uni.showToast({ 
              title: '取消预约成功', 
              icon: 'success' 
            })
            this.resetForm()
            this.$emit('cancelPppointment')
            this.submitText = '立即预约'
            // this.$emit('update:submitText', '立即预约')
            this
            
            // 取消预约成功后延迟返回上一页
            setTimeout(() => {
              uni.navigateBack({
                delta: 1,
                fail: () => {
                  // 如果返回失败，则跳转到首页
                  uni.switchTab({
                    url: '/pages/index/index'
                  })
                }
              })
            }, 1500) // 延迟1.5秒，让用户看到成功提示
          } else {
            uni.showToast({ 
              title: res.message || '取消预约失败', 
              icon: 'none' 
            })
          }
        } else {  
          // 创建预约
          const params = {
            warehouseId: this.formData.warehouseId,
            visitDate: this.formData.visitDate,
            visitTime: this.formData.visitTime,
            visitorCount: this.formData.visitorCount,
            contactName: this.formData.contactName,
            contactPhone: this.formData.contactPhone,
            email: this.formData.email,
            remarks: this.formData.remarks,
            belongCompany: this.formData.belongCompany,
            status: 0, // 默认待确认状态
            userId: this.formData.userId
          }
          
          const res = await API.appointment.create(params)
          console.log("预约接口返回:", res);
          if (res) {
            uni.showToast({ 
              title: '预约成功', 
              icon: 'success' 
            })
            this.$emit('appointmentSuccess')
            this.submitText = '立即预约'
            // 更新预约ID
            if (res.data && res.data.appointmentId) {
              this.formData.appointmentId = res.data.appointmentId;
            }
            
            // 预约成功后延迟返回上一页
            setTimeout(() => {
              uni.navigateBack({
                delta: 1,
                fail: () => {
                  // 如果返回失败，则跳转到首页
                  uni.switchTab({
                    url: '/pages/index/index'
                  })
                }
              })
            }, 1500) // 延迟1.5秒，让用户看到成功提示
          } else {
            uni.showToast({ 
              title: res.message || '预约失败', 
              icon: 'none' 
            })
          }
        }
      } catch (error) {
        console.error('提交失败:', error)
        uni.showToast({ 
          title: error.message || '提交失败，请重试', 
          icon: 'none' 
        })
      } finally {
        this.submitting = false
      }
    },
    resetForm() {
      this.formData = {
        appointmentId: null, // 预约ID
        warehouseId: this.warehouseId, // 仓库ID
        visitDate: '', // 预约日期 (对应后端的 visitDate)
        visitTime: '', // 预约时间 (对应后端的 visitTime)
        visitorCount: '1人', // 参观人数 (对应后端的 visitorCount)
        contactName: '', // 联系人姓名 (对应后端的 contactName)
        contactPhone: '', // 联系电话 (对应后端的 contactPhone)
        email: '', // 电子邮箱
        remarks: '', // 备注信息 (对应后端的 remarks)
        belongCompany: '', // 所属公司
        status: 0, // 预约状态（0待确认，1已确认，2取消）
        userId: null, // 申请人ID
      }
    },
    reset() {
      this.resetForm()
    },
    setFormData(data) {
      // 确保warehouseId正确设置
      if (this.warehouseId) {
        data.warehouseId = this.warehouseId;
      }
      
      // 获取用户信息设置申请人ID
      const userInfo = uni.getStorageSync('userInfo');
      if (userInfo && userInfo.id) {
        data.userId = userInfo.id;
      }
      
      this.formData = { ...this.formData, ...data }
    },
    getPeopleIndex() {
      const value = this.formData.visitorCount;
      const index = this.peopleRange.findIndex(item => item === value);
      return index >= 0 ? index : 0; // 如果找不到匹配项，默认返回0
    },
    
    getSubmitButtonText() {
      if (this.submitting) {
        return '提交中...'
      }
      return this.submitText
    }
  }
}
</script>

<style scoped>
.appointment-form {
  background: #f7f8fa;
  min-height: 100vh;
  padding: 24rpx 16rpx 100rpx 16rpx;
}

.title {
  font-size: 32rpx;
  font-weight: 600;
  color: #222;
  display: block;
  margin-bottom: 8rpx;
}

.address {
  font-size: 26rpx;
  color: #888;
}

.form-section {
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx 20rpx;
  box-shadow: var(--shadow-light);
}

.form-item {
  gap: 10rpx;
  margin-bottom: 24rpx;
  display: flex;
  align-items: flex-start;
  flex-direction: column;
}

.form-item text {
  width: auto;
  font-size: 28rpx;
  color: #333;
  flex-shrink: 0;
}

.picker {
  width: 100%;
  height: 92rpx;
  padding: 16rpx 24rpx;
  background: #fff;
  border-radius: 12rpx;
  color: #666;
  font-size: 28rpx;
  display: flex;
  flex: 1;
  border: 2rpx solid #e3e3e3;
  box-sizing: border-box;
  align-items: center;
}

.input {
  flex: 1;
  width: 100%;
  font-size: 28rpx;
  border: none;
  background: #fff;
  border-radius: 12rpx;
  padding: 16rpx 24rpx;
  border: 2rpx solid #e3e3e3;
  box-sizing: border-box;
  height: 60rpx;
}

.remark {
  width: 100%;
  min-height: 100rpx;
  padding: 16rpx 24rpx;
  box-sizing: border-box;
  border: 2rpx solid #e3e3e3;
  border-radius: 12rpx;
  font-size: 28rpx;
  color: #333;
  line-height: 1.5;
}

.time-grid {
  display: grid;
  width: 100%;
  grid-template-columns: repeat(3, 1fr);
  gap: 16rpx;
}

.time-chip {
  height: 80rpx;
  background: #fff;
  border: 2rpx solid #e3e3e3;
  border-radius: 12rpx;
  color: #333;
  font-size: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.time-chip.active {
  background: #C02C38;
  color: #fff;
  border-color: #C02C38;
}

.btn-primary {
  width: 100%;
  background: #C02C38;
  color: #fff;
  font-size: 32rpx;
  border: none;
  border-radius: 12rpx;
  padding: 24rpx 0;
  margin-top: 16rpx;
  font-weight: 600;
  box-shadow: 0 8rpx 20rpx rgba(192, 44, 56, 0.28);
  transition: all 0.3s;
}

.btn-primary:disabled {
  background: #ccc;
  box-shadow: none;
  opacity: 0.6;
}

.btn-disabled {
  background: #ccc !important;
  color: #999 !important;
  box-shadow: none !important;
  opacity: 0.6;
  cursor: not-allowed;
}
</style> 